import router from "../router/router";

const url = "http://localhost:4001/api";

function ajax(router, data, type) {
  var xhr = new XMLHttpRequest();
  xhr.addEventListener("load", loadHandler);
  xhr.open("post", url + "/" + router);
  if (type === "json") {
    data = JSON.stringify(data);
    xhr.setRequestHeader("Content-Type", "application/json");
  } else if (type === "query") {
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencode");
  }
  if (data) xhr.send(data);
  else xhr.send();
}

function loadHandler(e) {
  switch (this.responseURL.split("/").pop()) {
    case "register":
      var res = JSON.parse(this.response);
      if (res.result) {
        $(document).trigger("registerSuccess");
      } else {
        alert(res.reason);
      }
      break;
    case "auth":
      var res = JSON.parse(this.response);
      $(document).trigger("loginData", res);
      break;
    case "login":
      var res = JSON.parse(this.response);
      res.result ? $(document).trigger("login", res) : alert(res.reason);
      break;
    case "logout":
      $(document).trigger("logout");
      $("#listMenu").css("display", "none");
      break;
    case "delete":
      var res = JSON.parse(this.response);
      if (res.result) {
        alert("删除成功");
        $(document).trigger("delete", res);
      } else {
        alert("删除失败,请重试");
      }
      break;
  }
}

export default ajax;
